仅从JSON

时间:2017-01-15 23:34:03

标签: javascript json

我想只检索从Json到Javascript的非空值。

这是代码:

var words = [

{word: '', phrase: 'phrase1', url: 'url.1'},
{word: 'word2', phrase: '', url: 'url.2'},
{word: '', phrase: 'phrase3', url: 'url.3'},
{word: 'word4', phrase: 'phrase4', url: ''}

];
    var factIndex = Math.floor(Math.random() * words.length);
    var randomWordsIT = words[factIndex];
    var selectWordFromRandom = randomWordsIT.word;

 alert(selectWordFromRandom);

例如,if(selectWordFromRandom.isEmpty){random again}。

谢谢!

1 个答案:

答案 0 :(得分:0)

只需使用while循环,直到填充 selectWordFromRandom 变量。

var selectWordFromRandom = '';
while (selectWordFromRandom == ''){
    var factIndex = Math.floor(Math.random() * words.length);
    var randomWordsIT = words[factIndex];
    selectWordFromRandom = randomWordsIT.word;
}

alert(selectWordFromRandom);

另一种方法是预过滤数组以删除所有空值。