英文:
for loop wont work in a function inside react component
问题
import React from 'react';
const RowArray = () => {
return (
<div>
<h1>Row Array</h1>
</div>
);
};
const chunk_array = (list, integer) => {
let temp_arr = list;
console.log('chunks', list, 'integer', integer);
const list_of_chunks = [];
const iteration = Math.ceil(+list.length / +integer);
for (let i = 0; i < iteration; i++) {
console.log(i);
let temp_chunk = temp_arr.splice(6, temp_arr.length);
list_of_chunks.push(temp_chunk);
}
return list_of_chunks;
};
const TableArray = ({ details }) => {
const data = chunk_array(details);
console.log('data', data);
return (
<div className="d-flex flex-row">
<RowArray />
</div>
);
};
export default TableArray;
The issue in the provided code is that the for
loop in the chunk_array
function has an undeclared loop variable. To fix this, I added let i = 0
to initialize the loop variable i
. This should resolve the problem, and console.log(i)
will now log the loop variable's values.
英文:
import React from 'react';
const RowArray=()=>{
return(
<div>
<h1>Row Array</h1>
</div>
)
};
const chunk_array = (list, integer)=>{
let temp_arr = list;
console.log('chunks',list,'integer',integer);
const list_of_chunks = [];
const iteration = Math.ceil(+list.length/+integer);
// list.map(x => {console.log(x,"map")})
for (let i;i< iteration ;i++ ){
console.log(i);
let temp_chunk = temp_arr.splice(6, temp_arr.length);
list_of_chunks.push(temp_chunk);
};
return list_of_chunks;
}
const TableArray=({details})=>{
const data = chunk_array(details);
console.log('data', data);
return(
<div className="d-flex flex-row">
<RowArray/>
</div>
)
};
export default TableArray;
the for loop in function chunk array won't work, supported as no i was logged in the console. I understand in jsx for loop may not work, I believe I define the function in pure javascript enviroment, so why do you think it is?
Console.log(i) doesn't log anything, as in the function skipped for loop line
答案1
得分: 3
你还没有在 for
循环中初始化 i
的值
for (let i = 0; i < iteration; i++) {
// your code
}
chunk_array
函数需要两个参数,而你只传递了一个参数 details
英文:
you haven't initialized the value of i
in the for
loop
for (let i = 0; i < iteration; i++) {
// your code
}
chunk_array
function expects two arguments and you're only passing one argument details
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论