我正在尝试根据键值对中键的长度将以下数组从大到小排序:
[["Hello":"Goodbye"],["Yes":"No"],["He is going":"She is going"]]
这是我正在使用的代码无效:
makeArray.sort(function (a, b) {
return Object.keys(b).length - Object.keys(a).length;
});
console.log(makeArray);
我希望console.log读取:
[["He is going":"She is going"],["Hello":"Goodbye"],["Yes":"No"]]
答案 0 :(得分:1)
您正在计算键数,而不是查看第一个键。所以你很接近,只需要引用键数组的第一个索引。
struct Movie {
static let movies = [
Movie(name: "movie 1", image: "movie-1.png"),
Movie(name: "movie 2", image: "movie-2.png")]
let name:String
let image:String
}
class Person {
var movieIndex:Int = 0
var movie:Movie? {
get {
return Movie.movies[movieIndex]
}
}
}
var alex1 = Person()
alex1.movieIndex = 0
var alex2 = Person()
alex2.movieIndex = 1
alex1.movie?.name // "movie-1.png"
alex2.movie?.name // "movie-2.png"
但是根据你的评论,我认为你没有对象。
var makeArray = [{"Hello":"Goodbye"},{"Yes":"No"},{"He is going":"She is going"}];
makeArray.sort(function (a, b) {
return Object.keys(b)[0].length - Object.keys(a)[0].length;
});
console.log(makeArray);