使用push()添加元素后jQuery sort()失效及附加数字问题求助
问题分析与修复方案
问题原因
- 添加元素后末尾出现数字5:你写的
cars += cars.push(newcar);是错误操作。push()方法执行后会返回数组的新长度,原数组初始有4个元素,push后长度变为5,+=会把数组和数字5拼接成字符串,导致末尾出现5;同时let newcar = [prompt("Enter new car")]把输入值包装成了数组,push后会在原数组里嵌套子数组,不符合需求。 - sort()无法生效:上述操作把数组转换成了字符串,字符串没有
sort()方法,自然无法执行排序。
修正后的代码
<body> <button id="addbtn">Add cars to list</button> <p id="add"></p> <script> let cars = ["bmw", "honda", "toyota", "ford"]; $(document).ready(function(){ $("#addbtn").click(function(){ $("#add").show(1000); let newcar = prompt("Enter new car"); cars.push(newcar); cars.sort(); alert(cars); document.getElementById("add").innerHTML = cars; }) }) </script> </body>
关键修正点
- 去掉
newcar的数组包装,直接获取prompt返回的字符串 - 移除错误的
cars += cars.push(newcar);,改为直接调用cars.push(newcar);——push()会直接修改原数组,不需要拼接它的返回值 - 此时数组保持数组类型,
sort()可以正常执行,默认的字符串排序逻辑适合当前汽车品牌名称的排序需求
内容的提问来源于stack exchange,提问作者parz
相关产品推荐
相关产品推荐

