Home > other >  Error with splice method: can't define array index property past the end of an array with non-w
Error with splice method: can't define array index property past the end of an array with non-w

Time:09-09

I want to insert a string value inside an array with 3 string values randomly. But it gives this error in console:

*Uncaught TypeError: can't define array index property past the end of an array with non-writable length*

After assigning obj.incorrect_answers to answers, the length of the array will be 3, and I try to insert correct_answer(that is a string) in an index between 0 to 3.

It's desired part of my code:

export const Home = () => {
    const [id, setId] = useState(0);
    const dispatch = useDispatch();
    const obj = useSelector((state) => state.questions.data[id]);
    const fetchStatus = useSelector((state) => state.questions.status);
    if(obj){
        let answers = obj.incorrect_answers;
        answers.splice(Math.floor(Math.random()*4), 0, obj.correct_answer);
        console.log(answers);
    }

    useEffect(() => {
        if(fetchStatus === "idle"){
            dispatch(fetchQuestions());
        }
    }, [fetchStatus])

obj is received from the server, but I know it's received correctly because when I console.log obj.incorrect_answers it gives me an array from 3 strings and when I console.log obj.correct_answer it gives me a string, correctly. So I think I just have a problem with splice method.

Maybe, it is relevant to receive data from the server, but I can see received data in the console...

CodePudding user response:

An alternative way of getting the same result is to insert to the end of the array, then simply shuffle the array.

 if(obj){
        let answers = obj.incorrect_answers;
        answers.push(obj.correct_answer)
        answers.sort(() => Math.random() - 0.5)
        console.log(answers);
    }

CodePudding user response:

It fixed by slice(). Only by changing:

let answers = obj.incorrect_answers;

to

let answers = obj.incorrect_answers.slice();
  • Related