检查一个单词是否在数组的各个子区间内
Check if a word is within various sub-intervals of an array
我有一个单词数组(其中 25 个,0-24),我想在 for 循环中进行测试,检查随机选择的单词是否在区间 0-4、5-9、10 内-14 等..
我该怎么做?
else if (words[i > 4 && <= 9]){}
我在 for
循环中尝试了该行,但它给我一个语法错误。
Uncaught SyntaxError: Unexpected token <=
您的条件中缺少左侧比较。以此为条件:
i > 4 && i <= 9
但是请注意,您没有对这种情况做任何有用的事情。您的结果将类似于 words[true]
或 words[false]
.
更新
您现在已经详细说明了一点。如果我理解正确的话,你想从你的数组中随机选择一个词,然后算出它位于数组中的哪个 5 区间。
在下面的例子中,间隔被索引;所以 0 = 0-4、1 = 5-9、2 = 10-14 等等...
var words = [ "Synergetic", "unsteeped", "goldcup", "coronach", "swamper", "rehearse", "rusty", "reannotation", "dunne", "unblenched", "classification", "interpolation", "toper", "grisliest.", "Rechart", "imbower", "reilluminating", "glucagon", "interassuring", "parallelepipedon", "doyenne", "neenah", "tetragram" ];
function pickARandomWordAndCheckTheInterval(){
var randomIndex = Math.floor(Math.random() * words.length);
var word = words[randomIndex]
var interval = Math.floor(randomIndex / 5);
console.log('The random word is:' + word);
console.log('The interval is:' + interval );
}
pickARandomWordAndCheckTheInterval();
要解释它真的很简单,你只是忘了告诉语言什么需要小于或等于 9。
您假设它像人类一样处理逻辑条件(我们假设在 && 运算符之后您仍在考虑 i,但这不是 JS 解释器会做的)。
&& 后面需要是一个可以计算的表达式。 <= 9
不求值(它不被视为有效表达式,因为 <=
是一种二元运算符,需要两个操作数,一个在前面,一个在后面)。
对于 JS 解释器,它只是意味着 "less than or equal to 9"。但是 "less than or equal to 9" 是什么?你需要告诉它 "i is less than or equal to 9".
i > 4 && i <= 9
是正确的写法。
我有一个单词数组(其中 25 个,0-24),我想在 for 循环中进行测试,检查随机选择的单词是否在区间 0-4、5-9、10 内-14 等..
我该怎么做?
else if (words[i > 4 && <= 9]){}
我在 for
循环中尝试了该行,但它给我一个语法错误。
Uncaught SyntaxError: Unexpected token <=
您的条件中缺少左侧比较。以此为条件:
i > 4 && i <= 9
但是请注意,您没有对这种情况做任何有用的事情。您的结果将类似于 words[true]
或 words[false]
.
更新
您现在已经详细说明了一点。如果我理解正确的话,你想从你的数组中随机选择一个词,然后算出它位于数组中的哪个 5 区间。
在下面的例子中,间隔被索引;所以 0 = 0-4、1 = 5-9、2 = 10-14 等等...
var words = [ "Synergetic", "unsteeped", "goldcup", "coronach", "swamper", "rehearse", "rusty", "reannotation", "dunne", "unblenched", "classification", "interpolation", "toper", "grisliest.", "Rechart", "imbower", "reilluminating", "glucagon", "interassuring", "parallelepipedon", "doyenne", "neenah", "tetragram" ];
function pickARandomWordAndCheckTheInterval(){
var randomIndex = Math.floor(Math.random() * words.length);
var word = words[randomIndex]
var interval = Math.floor(randomIndex / 5);
console.log('The random word is:' + word);
console.log('The interval is:' + interval );
}
pickARandomWordAndCheckTheInterval();
要解释它真的很简单,你只是忘了告诉语言什么需要小于或等于 9。
您假设它像人类一样处理逻辑条件(我们假设在 && 运算符之后您仍在考虑 i,但这不是 JS 解释器会做的)。
&& 后面需要是一个可以计算的表达式。 <= 9
不求值(它不被视为有效表达式,因为 <=
是一种二元运算符,需要两个操作数,一个在前面,一个在后面)。
对于 JS 解释器,它只是意味着 "less than or equal to 9"。但是 "less than or equal to 9" 是什么?你需要告诉它 "i is less than or equal to 9".
i > 4 && i <= 9
是正确的写法。