js—reduce方法练习之无限引用对象的值

2022-07-01 19:11:46 浏览数 (1)

代码语言:javascript复制
<!DOCTYPE html>
<html>
<head>
    <title>数组的reduce方法</title>
</head>
<body>

</body>
<script type="text/javascript">
    var obj = {
        a:{
            b:{
                c:"maomin"
            }
        }
    }

    const safeGet = (obj, path) => {
        try {
          return path.split('.').reduce((o, k) => o[k], obj)
        } catch (e) {
          return undefined
        }
    }
  console.log(safeGet(obj,'a.b.c'));// maomin

  // 其他练习
    var str = "1,2,3,4";
    var arr = str.split(",");
    var newArr = arr.map(Number);
    console.log(newArr);
  var sum = newArr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev   cur;
},0)
// 0 1 0
// 1 2 1
// 3 3 2
// 6 4 3
</script>
</html>
1234567891011121314151617181920212223242526272829303132333435363738394041

更多内容请见原文,原文转载自:http://www.mark-to-win.com/tutorial/50906.html

0 人点赞