1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import React from 'react';
function get(obj, chain, defaultVal) { // 将链式属性路径拆分成数组 const keys = chain.split('.');
// 初始化结果为传入的对象 let result = obj;
// 遍历属性路径数组,并逐层获取属性值 for (let i = 0; i < keys.length; i++) { // 如果当前属性值为 undefined,则返回默认值 if (result[keys[i]] === undefined) { return defaultVal; }
// 否则,将结果更新为当前属性值 result = result[keys[i]]; }
// 返回最终结果 return result; }
function GetExample() { const data = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
// 测试 get 函数 const name = get(data, 'name'); // 'John' const city = get(data, 'address.city'); // 'New York' const zip = get(data, 'address.zip', 'N/A'); // 'N/A'
return ( <div> <h1>get() 函数示例</h1> <p>Name: {name}</p> <p>City: {city}</p> <p>Zip: {zip}</p> </div> ); }
export default GetExample;
|