为什么这段代码没有正确地将单词推送到答案数组?当我将循环更改为:
for (var k in testDict) {
console.log(testDict[k].split("").sort());
}
它正确地打印了我所期待的内容,这是一系列拆分,排序的字符。所以我不确定为什么它没有评估平等和推动回答。谢谢!
function word_unscrambler(word, dict) {
var testDict = dict;
var answer = [];
var word_scrambled = word.split("").sort();
for (var k in testDict) {
if (word_scrambled === testDict[k].split("").sort())
answer.push(testDict[k]);
}
console.log(answer);
}
word_unscrambler("kevin", ["trees", "but", "ankle", "nevik", "knive", "evin"]);
答案 0 :(得分:3)
问题是你正在测试数组是否相等,因为你正在使用字符串,你可以加入两个被比较的数组:
function word_unscrambler(word, dict) {
var testDict = dict;
var answer = [];
var word_scrambled = word.split("").sort().join('');
for (var k in testDict) {
if (word_scrambled === testDict[k].split("").sort().join(''))
answer.push(testDict[k]);
}
console.log(answer);
}
答案 1 :(得分:1)
您无法使用==来比较数组 有关问题的详细信息和解决方案,请参阅此页面:How to check if two arrays are equal with JavaScript?
答案 2 :(得分:0)
您不能直接比较数组的相等性,因为它只会比较它们的指针。您必须比较数组的内容。只要您不处理多维数组,这就足够了:
function word_unscrambler(word, dict) {
var testDict = dict;
var answer = [];
var word_scrambled = word.split("").sort();
for (var k in testDict) {
if (arrays_equal(word_scrambled, testDict[k].split("").sort()))
answer.push(testDict[k]);
}
console.log(answer);
}
function arrays_equal(arr1, arr2) {
for (var i in arr1) {
if (arr1[i]!==arr2[i])
return false;
}
return true;
}
word_unscrambler("kevin", ["trees", "but", "ankle", "nevik", "knive", "evin"]);