简体   繁体   中英

Is it correct or not array.concat() method

I created concat function similar to Array.concat(). It is passing all my tests:

  1. return new array only passing array argument.
  2. passing two parameters second one is string.
  3. passing two parameters second one is array.
  4. passing two parameters second one is number.
  5. passing three parameters second is number, third is string.
  6. passing four arguments.
function concat() {
  var result = [];

  for (var i = 0; i < arguments.length; i++) {
    result.push(arguments[i]);
  }

  return result;
}

This is more like Array.of as mentioned in comments:

 console.log(Array.of(1, 2, 3));

But you can make the exact same functionality much more concise with rest parameters and the implicit return of arrow functions:

 const concat = (...a) => a; console.log(concat()); console.log(concat(1, 2, 3));

Although, since it is Array.of , it's so much easier just to assign the function reference:

 const concat = Array.of; console.log(concat()); console.log(concat(1, 2, 3));

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