简体   繁体   中英

How to remove element using splice?

I am not able to pass this test.

The result is undefined .

How do I solve the problem?

Code:

mocha.setup('bdd');
var expect = chai.expect;

function removeEnd(arr, n) {
/*
    write a program remove n element last of an array
*/
var removedItems= arr.splice(arr.length-n, n);

}

console.log(removeEnd([2, 3, 1, 8, 9, 7], 3));

describe('removeEnd', () => {
  it('Remove n elements from the endof an given array', () => {
    expect(removeEnd([2, 3, 1, 8, 9, 7], 3)).to.eql([2, 3, 1]);
  });
});

mocha.run();

You need to use slice() , not splice() :

function removeEnd(arr, n) {
    return arr.slice(0, arr.length - n);
}

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