首页 > 解决方案 > arguments 对象的长度为零,即使我可以访问它的属性

问题描述

为什么当我将参数传递给函数甚至可以访问它的属性时,参数对象的长度为零?我说的是所有 javascript 函数都实现的 arguments 对象,您可以从中访问函数参数。您可以在这里了解更多信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments 。

发生的情况是,当我将 arguments 对象的长度打印到控制台时,它说它有 cero 长度,但是当我从我的函数(组件)内部访问它时,我仍然可以使用它的一个属性。您可以阅读下面代码中的注释以获取更多详细信息。

我正在使用对打字稿做出反应。

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>

  );
}

标签: javascriptreactjstypescript

解决方案


我不确定你的问题?

您是否尝试通过执行arguments[0].id来访问id 道具

您可以通过以下方式访问组件的“参数”(在 react 中称为 props):

更换:

export const Buttons: React.FC<Props> = function(){

经过:

export const Buttons: React.FC<Props> = function(props){

并打电话

props.id

祝你好运


推荐阅读