HarmonyOS 鸿蒙Next 遍历数组里的对象 找到包含某个属性的对象
HarmonyOS 鸿蒙Next 遍历数组里的对象 找到包含某个属性的对象
for (let index = 0; index < obj.length; index++) {
if (obj[index].district.concat(‘北京’)) {
LogUtil.error(“找到北京=” + obj[index].district)
LogUtil.error(“找到北京 cody=” + obj[index].district_geocode)
}
}
java里有contains方法,遍历找到对象里包含的属性,鸿蒙里我没有找到相应的办法,请问一下有什么解决办法嘛?
if (obj[index].district.concat(‘北京’)) {
LogUtil.error(“找到北京=” + obj[index].district)
LogUtil.error(“找到北京 cody=” + obj[index].district_geocode)
}
}
java里有contains方法,遍历找到对象里包含的属性,鸿蒙里我没有找到相应的办法,请问一下有什么解决办法嘛?
2 回复
interface CatInfo {
age: number;
name: string;
}
let cat1: CatInfo = { age: 10, name: "red" };
let cat2: CatInfo = { age: 5, name: "real" };
let cat3: CatInfo = { age: 16, name: "ren" };
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
[@State](/user/State) message: string = 'Hello World';
arr: Array<CatInfo> = [cat1, cat2, cat3]
build() {
Column() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
for (let index = 0; index < this.arr.length; index++) {
let aaa: ESObject = this.arr[index]
console.log("aaaaaaa" + aaa)
if (aaa['name'].includes("re")) {
console.log("我找到小猫red了!!")
}
}
let StringA: string = 'test';
let StringAB: string = 'newtest'
let isContain: boolean = StringAB.includes(StringA)
console.log('isContain:' + isContain)
})
}
.height('100%')
.width('100%')
}
}
在HarmonyOS鸿蒙Next中遍历数组并查找包含特定属性的对象,你可以使用JavaScript(如果在JS环境中开发应用)或Java(如果在Java环境中开发应用)。以下是两种语言的示例代码:
JavaScript示例
let array = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
let targetId = 2;
let result = array.find(obj => obj.id === targetId);
if (result) {
console.log('Found object:', result);
} else {
console.log('Object not found');
}
Java示例
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
class MyObject {
int id;
String name;
MyObject(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
List<MyObject> array = new ArrayList<>();
array.add(new MyObject(1, "Alice"));
array.add(new MyObject(2, "Bob"));
array.add(new MyObject(3, "Charlie"));
int targetId = 2;
Optional<MyObject> result = array.stream().filter(obj -> obj.id == targetId).findFirst();
if (result.isPresent()) {
System.out.println("Found object: " + result.get());
} else {
System.out.println("Object not found");
}
}
}
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html