【发布时间】:2020-04-09 12:46:28
【问题描述】:
为什么当我将参数传递给函数时,甚至当我可以访问它的属性时,参数对象的长度为零? 我说的是所有 javascript 函数都实现的 arguments 对象,您可以从中访问函数参数。您可以在这里了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments。
发生的情况是,当我将 arguments 对象的长度打印到控制台时,它说它有 cero 长度,但是当我从我的函数(组件)内部访问它时,我仍然可以使用它的一个属性。您可以阅读下面代码中的 cmets 了解更多详细信息。
我正在使用对打字稿做出反应。
interface Props{
id: string;
className?: string;
}
export const Buttons: React.FC<Props> = function(){
function arg(){
console.log("Funciona");
console.log("arguments object: "+arguments);
{/*This prints to the console that the arguments objects is of cero (0) length*/}
{/*Even when is posible to access
the id property that I have passed from App component*/}
console.log("arguments object: "+arguments.length);
console.log("arguments object: "+arguments[0]);
for(let i=0; i < arguments.length; i++){
{/*It will never enter the for loop*/}
console.log("arguments object: "+arguments[i]);
}
}{/*end arg*/}
React.useEffect(
()=>{
window.setTimeout(arg, 5000);
},
[]
);
return(
{/*This will work as I'm able to see the id from the dev tools*/}
<section id={arguments[0].id}>{}
<div className="container">
<p>Hello World</p>
</div>
</section>
);
}
这里我传递了 id 属性:
const App: React.FC = () => {
return (
<div className="App">
<Buttons id="buttons" />
</div>
);
}
【问题讨论】:
-
不要在您的帖子中添加垃圾文本来绕过要求您解释更多问题的要求 - 相反,请更详细地解释问题,例如作为您尝试过的哪种调试不起作用。查找如何创建 minimal reproducible example 也可能会有所帮助 - 考虑删除与问题不直接相关的代码。
-
@CertainPerformance 所有代码都与问题相关,但是是的,我将添加更多细节,因为我意识到问题尚不清楚。
标签: javascript reactjs typescript