加入時出現奇怪的問題。它適用于初始陣列,但不適用于過濾后的陣列。還測驗了字串的函式,但 resultA 也不是字串。
代碼有什么問題:
const constants = [2, 2, 4, 2, 6, 4, 7, 8];
const stdFound = [];
// Makes list of indexes - positions from matching value 2 in constants
constants.filter(function(elem, index, array) {
if (elem == (2)) {
stdFound.push(index);
}
});
//Makes new array from results by indexes found
const resultA = [constants.filter((x, i) => stdFound.includes(i))];
document.getElementById("resultA").innerHTML = resultA;
//Makes string by join
document.getElementById("resultJ").innerHTML = resultA.join(" x ");
<p> ARRAY : <span id="resultA"></span>
<p> JOIN x : <span id="resultJ"></span></p>
現在,這段代碼的結果是: ARRAY : 2,2,2 JOIN x : 2,2,2
很明顯, join 不起作用。
uj5u.com熱心網友回復:
filter()已經回傳一個陣列。無需在此包裝[]。
console.log(resultA) 將表明。
const constants = [2, 2, 4, 2, 6, 4, 7, 8];
const stdFound = [];
// Makes list of indexes - positions from matching value 2 in constants
constants.filter(function(elem, index, array) {
if (elem == (2)) {
stdFound.push(index);
}
});
//Makes new array from results by indexes found
const resultA = constants.filter((x, i) => stdFound.includes(i));
document.getElementById("resultA").innerHTML = resultA;
//Makes string by join
document.getElementById("resultJ").innerHTML = resultA.join(" x ");
<p> ARRAY : <span id="resultA"></span>
<p> JOIN x : <span id="resultJ"></span></p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315217.html
標籤:javascript 加入
下一篇:根據行值更改連接條件
