最近遇到的几个 JavaScript 题,附答案!

题1. 将数组 arr 转换成 newArr.

let arr = [
  [ 1, 5, 9, 13 ],
  [ 2, 6, 10, 14 ],
  [ 3, 7, 11, 15 ],
  [ 4, 8, 12, 16 ]
]
// =>>
let newArr = [
  [ 1, 2, 3, 4 ],
  [ 5, 6, 7, 8 ],
  [ 9, 10, 11, 12 ],
  [ 13, 14, 15, 16 ]
]

解题1:

let arr = [
  [ 1, 5, 9, 13 ],
  [ 2, 6, 10, 14 ],
  [ 3, 7, 11, 15 ],
  [ 4, 8, 12, 16 ]
]

let newArr = []

// 解法1:
arr.forEach(function (value, index) {
  newArr[index] = []
})

arr.forEach(function (value) {
  value.forEach(function (value, index) {
    newArr[index].push(value)
  })
})

// console.log(newArr)

// 解法2:
let t = []

arr.forEach(function (value1, index1) {

  value1.forEach(function (value2, index2) {

    t.push(arr[index2][index1])

  })

  newArr.push(t)
  t = []
})

// console.log(newArr)

题2. 输出 tree 的所有children

let tree = [
  {
    name: '001',
    children: [
      { name: 'name > 1' },
      { name: 'name > 1' }
    ]
  },
  {
    name: '002',
    children: [
      { name: 'name > 1' },
    ]
  },
  {
    name: '003',
    children: [
      {
        name: 'name > 1',
        children: [
          { name: 'name > 2' },
          { name: 'name > 2' }
        ]
      }
    ]
  }
]

解题2:

tree.forEach(function (value1) {
  console.log(value1.name)

  value1.children.forEach(function (value2) {
    console.log(value2.name)

    if (value2.children) {
      value2.children.forEach(function (value3) {
        console.log(value3.name)
      })
    }
  })
})

题3. 打印任意等边三角形,如下示例:

    *
   * *
  * * *
 * * * *
 ...

解题3:

function star(r) {
  for(var l=0;l<r;l++){
    var row=""

    for(var n=r; n > l; n--) {
      row+=" "
    }

    for(var i=0;i<=l;i++){
      row+="* "
    }

    console.log(row);
  }
}

star(5)

 

 

 

原文:最近遇到的几个 JavaScript 题,附答案!  链接:https://davidkoojohn.github.io/share/js-demo#

posted @ 2018-01-23 15:23  Baiyr  阅读(159)  评论(0编辑  收藏  举报