简体   繁体   中英

I need my array to return and array back to another variable while also including its previous array members, no idea how to go about it

This is the test code that it's supposed to pass

function makeArray() {
    const array = [];
    const t = 10;

    for (let i = 0; i < t; i++) {
        array.push("I am a strange loop.");
    }

    return [array, t];
}

describe('loops', () => {
    jsdom({
        src: fs.readFileSync(path.resolve(__dirname, '..', 'loops.js'), 'utf-8'),
    });

    describe('forLoop(array)', () => {
        it('adds `"I am ${i} strange loop${i === 0 ? \'\' : \'s\'}."` to an array 25 times', () => {
            const [array, t] = makeArray();
            const strangeArray = forLoop(array);
            const testArray = strangeArray.slice(array.length);

            const first = "I am 1 strange loop.";
            const rest = "I am 24 strange loops.";

            expect(strangeArray[11]).to.equal(first);
            expect(strangeArray[34]).to.equal(rest);
            expect(strangeArray.length).to.equal(t + 25);
        });
    });
});

this is my code to return the function to strangeArray what I am thinking is that 35 is the total number of members in the array and as the test pass requires me to have 'expect(strangeArray[11]).to.equal(first)' 11th value to be equal to my function return as "I am 1 strange loop."

function forLoop(array) {
    for (let i = 0; i < 35; i++) {
        if (array[i] === "I am a strange loop.") {
            return;
        }
        else {
            array.push("I am ${i} strange loops.");
        }
    }
    return [array,i];
}

Not sure what you mean exactly but I guess you just want the test to pass? The problem is that the first loop has 'loop' as singular and your indexes don't work either since they would start at 11. That's why your code doesn't work. You can just push to the original array.

function forLoop(array){
  for(let i = 0; i < 25; i++){
    array.push(`I am ${i} strange loop${i > 1 ? '' : 's'}.`)
  }
  return array
}

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