[英]Copy array and remove strings? Javascript
我正在嘗試制作一個沒有帶有“x”的所有字符串的數組副本,並將沒有這些“x”字符串的新數組歸因於下面的(deCode)變量。 使用 for 循環或 push/pop 或 join/split 方法。 誰能指出我正確的方向? 謝謝你
var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', '\'', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
var deCode = [];
如果您需要使用 for 循環,您可以遍歷數組並將每個元素推送到新數組。
var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', '\'', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
var deCode = [];
for (let i = 0; i < messageL.length; i ++) {
if (messageL[i] !== "x") {
deCode.push(messageL[i]);
}
}
不過,還有更好的辦法。 Javascript 有一個過濾方法,它可以讓你得到一個新數組,其中包含通過測試 function 的舊數組中的每個元素。
var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', '\'', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
// The .filter function passes every element to the function that you provide. If the function returns true, then that element is copied into a new array. Otherwise, it is not. Note that it doesn't modify the old array
var deCode = messageL.filter(function (letter) {
return letter !== "x"
});
您實際上可以通過使用箭頭 function來進一步縮短它。 這段代碼做同樣的事情:
var messageL = [ 'W', 'x', 'e', 'c', 'x', 'o', 'm', 'x', 'x', 'e', '\'', 'x', 's', ' ', 'h', 'o', 'x', 'm', 'x', 'x', 'e'];
var deCode = messageL.filter((element) => element !== "x");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.