簡體   English   中英

Javascript Function 和 const 數組

[英]Javascript Function and const array

我的運動有問題:

const negativeNumbers = [];
function extractNegativeNumbers(numbers) {
    if (numbers<0){
        console.log("It's negative number")
    } else {
        console.log("It's not negative number")
    }
}

我不知道如何將我的函數結果 append 轉換為 const 數組。 我應該使用哪個運算符來執行此操作?

你應該使用Array.prototype.push

編輯:如果您的numbers參數是一個數組而不是單個值,則使用以下內容檢查每個項目和 append 它:

const negativeNumbers = [];
function extractNegativeNumbers(numbers) {
    numbers.forEach(num => {
        if (num < 0) {
            console.log("It's negative number");
            negativeNumbers.push(num);
        } else console.log("It's not negative number");
    });
}

在這種情況下,您不使用運算符,而是使用屬於Array object 的內置 function 推送。

其他一些提到使用letvar代替,但兩者都不是必需的,因為數組對象是可變的。 這意味着更新數組的項目實際上並不會改變變量的值,因為變量仍然設置為相同的數組 object(不管數組包含什么)。 在這種情況下,添加const關鍵字所做的只是防止您將變量negativeNumbers重新分配給不同的值

你的 function 沒有意義。 如果要接收一個名為 numbers 的數組和 append 到您的 const 數組,那么它應該是:

function extractNegativeNumbers(numbers) {
    for (let num of numbers)
        if (num < 0)
            negativeNumbers.push(num);
}

請注意,即使您的數組是恆定的,它的項目也可以更改。 const會阻止您為變量重新分配值,但不會阻止您將項目添加到數組中。 另外,如果negativeNumbers.push(num); 不合你的口味,你可以使用negativeNumbers[negativeNumbers.length] = num; 反而。

使用 let 聲明數組,因為 const 用於聲明常量。

let negativeNumbers = [];

您可以使用 push function 添加元素。

negativeNumbers.push(number +' is a negative number');

如需進一步參考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

這是有關如何執行此操作的示例

 const numbers = [13, 3, -4, 78, -14, 12, -8], negativeNumbers = numbers.filter(n => n < 0); console.log(negativeNumbers);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM