JavaScript类数组转换为数组 面试题
1、JavaScript类数组转换为数组
(1)方法一:借用slice
(2)方法二:Array.from
2、代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>JavaScript类数组转换为数组</title>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
//NodeList伪数组
var div = document.getElementsByTagName('div')
//方法一:借用slice方法
function convertArray(obj) {
return Array.prototype.slice.call(obj);
}
//方法二:使用ES6
function convertArray2(obj) {
return Array.from(obj);
}
console.log(convertArray(div));
console.log(convertArray2(div));
</script>
</body>
</html>
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!