我想创建一个由名称组成的字符串数组
function namesOnly(arr) {
}
namesOnly([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
])
// expect: ["Angelina Jolie", "Eric Jones", "Paris Hilton", "Kayne West", "Bob Ziroll"]
所以希望!
答案 0 :(得分:1)
class Course < ApplicationRecord belongs_to :super_course, inverse_of: :courses after_update :destroy_empty_super_course ... private def destroy_empty_super_course id = super_course_id_changed? ? super_course_id_was : super_course_id super_course = SuperCourse.find(id) super_course.destroy if super_course.courses.empty? end end
方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。
rspec
尽管我认为context "when super_course is updated" do
let(:super_course) { create(:super_course, courses: []) }
let(:course) { create(:course, super_course: super_course) }
let(:new_super_course) { create(:super_course, courses: []) }
let(:new_course) { create(:course, semester: course.semester, subject: course.subject, super_course: new_super_course) }
subject { course.update!(super_course: new_super_course) }
it "should remove old super_course" do
expect { subject }.to change(SuperCourse, :count).by(-1)
end
end
更适合这里,但您也可以使用map()
循环:
function namesOnly(arr) {
return arr.map(i => i.name);
}
var res = namesOnly([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
])
console.log(res);
答案 1 :(得分:0)
您可以使用forEach并推动创建结果
@model IEnumerable<MvcProject.Models.EmployeeModel>;
@foreach (var item in Model)
{
}
function namesOnly(arr) {
var result = [];
arr.forEach(c=> { result.push(c.name); });
console.log(result);
return result;
}
答案 2 :(得分:-1)
您可以使用Array.map组成一个新数组。
function namesOnly(arr) {
return arr.map(element => { return element.name; });
}
答案 3 :(得分:-1)
function makeStrings(arr){
let str = arr.map(function(s) {
if(s.age >= 17) {
return s.name + 'can go to The Matrix';
} else if(s.age) {
return s.name + 'is under age!';
}
})
return str;
}