为什么 ({"word"}) return 它的长度?

Why does ({"word"}) return its length?

我对这个查找字符串长度的解决方案感到困惑:

const getLength = ({length}) => length

我熟悉对象和数组的解构,但找不到任何关于字符串解构(?)的信息,也不知道这 return 的长度。在函数参数中添加花括号的概念对我来说也是陌生的。

您正在创建一个函数,该函数请求将对象参数解构为其 "length" 属性。当您传递一个字符串时,该字符串将被强制转换为一个 String 实例,因此您将获得 "length" 属性 值,函数 returns.

看看当你尝试这个时会发生什么:

console.log(getLength({ length: "Hello world" }));

const getLength =

开始为 getLength 常量赋值,然后

({length})

destructuring assignment MDN 获取输入参数并解包长度 属性 值,最后

=> length

箭头函数returns引用长度值


const getLength = ({length}) => length;

document.querySelector("#b").onclick = function(){
 document.querySelector("#d").innerText = getLength(document.querySelector("#i").value);
};
<input id="i" /><input type="button" id="b" value="Try Me" /><br>
<div id="d"></div>