简体   繁体   中英

Is it possible to use array.splice(argument[i], x) to edit an array for variables that meet a condition?

Key Question

-How do you use splice(argument[i], x)? Can it be used this way or am I only allowed to use numbers? ie (1, 2), (3, 0)

-I'm a little unsure of when element[i] can be used when an array is declared. So it can be used for both for loops and while loops when setting conditions? Can it be used as an argument or parameter in functions or additional methods besides splice?

What I want to do

-Write a function called "isEven".

-Given an array of numbers, "isEven" returns a new array.

-Only even numbers are outputted from the input array.

ex. var output = isEven([1, 4, 5, 6, 10, 13]);

console.log(output); // --> [4, 6, 10]

Approach

-declare var digits to "catch" the array input.

-declare var NewArray for return of output array,

-use if condition to go through var digits and splice the variable at any given index.

-declare NewArray to the newly spliced array

function isEven(num) {
  var digits = num;
  var newArray = [];
  digits.forEach(function(num) {
    if (num[i] % 2 > 0) {
      newArray = digits.splice(num[i], 1);
    }
  }) return newArray;
}

var ledoit = isEven([1, 4, 6]);
console.log(ledoit);

You want to use the % operator:

 var nums = [1, 4, 5, 6, 10, 13]; function getEvens(array){ for(var i=0,n,a=[],l=array.length; i<l; i++){ n = array[i]; if(n % 2 === 0)a.push(n); } return a; } console.log(getEvens(nums)); 

Albeit, not backward compatible, you could also do:

 var nums = [1, 4, 5, 6, 10, 13]; function getEvens(array){ return array.filter(n => (n % 2 === 0)); } console.log(getEvens(nums)); 

Try this:

function isEven(myArray) {
    return myArray.filter(item => {
        return Number.isInteger(item / 2)
    })
}

Then isEven([1, 4, 5, 6, 10, 13]) will output [4,6,10]

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