我正在尝试推入一个初始为空的数组,条件是两个不同的非空数组的两个不同索引处的内容不具有相同字符,并且初始为空的数组尚未提前将该字符推入
我尝试使用not运算符,contains,includes,但是似乎没有任何作用。
var pushToArray = [];
for (var i = 0; i < 5; i++) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (characters[i] != moreCharacters[randomIndex] && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
if(arrayContent1("I") == arrayContent2("I"))
然后不要按下
pushToArray
的预期结果示例: ["F", "R", "E", "D", "L"]
pushToArray
的实际结果: ["I", "F", "R", "D", "Y"]
我不要在那儿的字母“ I”
答案 0 :(得分:1)
测试
if (characters[i] != moreCharacters[randomIndex]
仅当characters[i]
是所选择的字符时才会失败-听起来您想确保characters
的 none 都与所选择的字符匹配:
if (!characters.includes(moreCharacters[randomIndex])
如果仅是有条件地推送到数组,则将for
循环更改为
while (pushToArray.length < 5) {
var pushToArray = [];
while (pushToArray.length < 5) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not already in there
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
但是,如果您事先从characters
中过滤出moreCharacters
,则逻辑会更容易遵循:
const excludeChars = ["M", "U", "S", "I", "C"];
const inputChars = ["F", "R", "I", "E", "N", "D", "L", "Y"]
.filter(char => !excludeChars.includes(char));
const result = [];
for (let i = 0; i < 6; i++) {
const randIndex = Math.floor(Math.random() * inputChars.length);
const [char] = inputChars.splice(randIndex, 1);
result.push(char);
}
console.log(result);
答案 1 :(得分:1)
此代码执行以下操作:
我希望array3仅包含来自array2的,不在array1中的字母。我基本上不希望array1中存在任何字母
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushToArray = [];
var i, l = characters.length;
for (i = 0; i < l; i++) {
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
答案 2 :(得分:1)
这可以简单地通过执行以下操作来实现:
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushedToArray = [...characters].filter(x => moreCharacters.indexOf(x) === -1);
var finalArray = pushedToArray.filter((item, index) => pushedToArray.indexOf(item) === index);