使用array.length创建新数组

时间:2017-08-17 21:13:04

标签: javascript

如何以数字方式对array.length进行排序?在this image中,我的数字生成器应按降序排列。

我尝试使用push函数创建一个新数组。我的代码如下:

var newArray = [];
newArray.push(myArray.length);

不幸的是,这不起作用。我是javascript的初学者,但我还没能找到另一种解决方案。



<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script src="hack.js" defer></script>
	</head>
<body>
	<div id="demo" style="width: 500px;border: 1px solid black;"></div>
  <script>
    var myNumbers = '';
for (var i = 10; i <= 40; i++) {
	var myArray = [];
	for (var j = 2; j < i; j++) {
		if (i % j == 0) {
			myArray.push(j);	
		}
	}
	myNumbers += "<p>" + i + " number of generators = " + myArray.length + '</p>';

}

document.getElementById("demo").innerHTML = myNumbers;
  </script>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

var myNumbers = [];
for (var i = 10; i <= 40; i++) {
    var myArray = [];
    for (var j = 2; j < i; j++) {
        if (i % j == 0) {
            myArray.push(j);    
        }
    }
    var value = { int: i, length: myArray.length, html:"<p>" + i + " number of generators = " + myArray.length + '</p>' }
    myNumbers.push(value);

}
myNumbers.sort(function(a, b){
  return b.length - a.length;
});

document.getElementById("demo").innerHTML = myNumbers.map(function(d) { return d['html']; }).join('')

答案 1 :(得分:0)

首先,您可以在一个对象数组中存储数字和它们的生成器计数的映射。然后,您可以使用比较器函数对此数组进行排序。对此数组的迭代根据此排序数组添加元素。

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script src="hack.js" defer></script>
	</head>
<body>
	<div id="demo" style="width: 500px;border: 1px solid black;"></div>
  <script>
    var myNumbers = '', myArray = [];
for (var i = 10; i <= 40; i++) {
    var count = 0;
	for (var j = 2; j < i; j++) {
		if (i % j == 0) {
			count++;
		}
	}
    myArray.push({number: i, generators: count});
}
myArray.sort(function(a,b){
    return b.generators - a.generators;
});
for(var i=0; i<myArray.length; i++)
    myNumbers += "<p>" + myArray[i].number + " number of generators = " + myArray[i].generators + '</p>';

document.getElementById("demo").innerHTML = myNumbers;
  </script>
</body>
</html>
&#13;
&#13;
&#13;