[英]Javascript. I am trying to use .findIndex() but I get the following message: TypeError: a is not a function
我有 'array magazine' 和 'string ransomNote'。 並希望根據字符串中的元素訪問數組的元素。
這就是我正在嘗試的:magazine.findIndex(ransomNote[i])
var canConstruct = function(ransomNote, magazine){
magazine = magazine.split('');
//console.log(magazine);
for(let i = 0; i < ransomNote.length; i++){
if (magazine.includes(ransomNote[i])){
element_to_erase = magazine.findIndex(ransomNote[i]);
magazine = magazine.splice(element_to_erase , 1);
//console.log(magazine);
continue;
} else {
return false;
}
}
return true;
};
console.log(canConstruct('aa', 'aab'));
findIndex
將 function 作為參數,並且您傳遞給它一個字符串
你需要做
magazine.findIndex((magazineString) => magazineString === ransomNote[i])
或者只是在注釋中使用indexOf
,並可能驗證在任何一種情況下它是否返回-1
(indexOf) 或undefined
(findIndex) 以外的值。
您可以直接使用magazine.search
,而不是將輸入字符串magazine
轉換為數組 -
const removeCharAt = (str = 0, pos = 0) => str.substr(0, pos) + str.substr(pos + 1) const canConstruct = (ransomNote = "", magazine = "") => { for (const char of ransomNote) { const pos = magazine.search(char) if (pos >= 0) magazine = removeCharAt(magazine) else return false } return true } console.log(canConstruct('aa', 'aab')) // true console.log(canConstruct('az', 'aab')) // false console.log(canConstruct('stay inside', 'diet coke on sale this sunday')) // true
還有一個問題。 拼接時,您不需要重新分配。 拼接修改同一個數組。
您可以使用array.ever來簡化。
var canConstruct = function (ransomNote, magazine) { magazine = magazine.split(""); return ransomNote.split("").every((rChar) => { const rIndex = magazine.indexOf(rChar); if (rIndex.== -1) { magazine,splice(rIndex; 1); return true; } }); }. console,log(canConstruct("aa"; "aab")). console,log(canConstruct("az"; "aab"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.