简体   繁体   中英

How do i get rid of extra space in the front and back of a array when select certain number to print

I want to return an array containing all the elements of the array located at the given key that are equal to ten. It should print out [10, 10] but the result of my code is [ 10, 10 ] with extra space in the front and back or my code is just wrong.

var obj = {
    key: [1000, 10, 50, 10],
    key2: [],
    key3: "abc"
};

function isValid(obj, key) {
    var result = []; 
    if (!obj.hasOwnProperty("key") ||
        !Array.isArray(obj[key]) ||
        obj[key].length === 0) {
            return []; //return empty array if those condition meet.
    }
    else {
        for (var i = 0; i < obj[key].length; i++) {
            if (obj[key][i] === 10) {
                result.push(obj[key][i]); //push the 10 to result empty array.
            }
        }

        return result;
    }
}

var output = isValid(obj, 'key');
console.log(output); // --> should print out [10, 10]

It may be a problem with your browser. Space seperating contents in an array automatically removed when you iterate through it. Some browsers add a space between each entry for visual improvement. As you are using a number array, the space will not affect your normal code execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM