第四篇就记录一些常用表达式吧。
其实跟别的语言也差不多,都是那些东西,只是写法有略微的不同,用的熟了就可以了。
这里记下来,以后忘记了可以来查找。
1、Text里的特殊符号
正常Text两端都用引号包上,如果Text内部还有引号,就需要【\】进行转义。’
message = "我的公众号是\"规划GIS会\"";
Arcade还提供另一法,两端用【`】包上,里面的符号就可以随意用了。
message = `我的公众号是"规划GIS会"`;
换行符,一般情况下用【\n】就行了:
list = "Corn: 5,000\nWheat: 4,000\nRice: 2,000\nOther: 500\n";
或者用【TextFormatting.NewLine】,感觉比较麻烦,不如【\n】:
list = "Corn: 5,000" + TextFormatting.NewLine
"Wheat: 4,000" + TextFormatting.NewLine
"Rice: 2,000" + TextFormatting.NewLine
"Other: 500" + TextFormatting.NewLine;
一些其它类型的值,如果有转为Text,一般情况下可以在前面加【$】处理:
`There are ${$feature.STUDENTS} students at ${$feature.UNIVERSITY}.`
var scores = [70, 85, 92, 98, 100, 78, 89];
`The average score was ${Round(Average(scores), 2)}%.`
2、Functions
// 定义方法
function calculatePercentage(num, dem) {
var places = 2;
return Round((num / dem) * 100, places);
}
// 调用方法
calculatePercentage(50,75);
3、If - else
var x = 10;
if(x > 5){
return x + " is greater than 5";
} else {
return x + " is less than 5 or equal to 5";
}
Arcade提供了一些类似if-else的函数,像【IIF、Decode、When】等,在本系列文章的第二篇里有记录,可以复习一下。
4、For
最基础的【for】循环如下:
var result = 0;
for(var z=0; z < 100; z++) {
result += z;
}
return result; // returns 4950
【for...in】的写法:
// 数组
var myArray = [10,20,30];
var result = 0;
for(var index in myArray) {
result += myArray[index];
}
return result; // returns 60
// 字典
var myDictionary = Dictionary("field1", 1, "field2", 2);
var n = 0;
for(var k in myDictionary) {
n += myDictionary[k];
}
return n; // returns 3;
// 要素
Expects($feature, "*");
var n = 0;
for(var attribute in $feature) {
n += $feature[attribute];
}
return n;
// 要素集
var sensitiveFeatures = Filter($layer, "class = 'sensitive'");
var largeAreasPresent;
for(var f in sensitiveFeatures){
largeAreasPresent = iif(f.ACRES > 5000, true, false);
}
return largeAreasPresent;
5、Break、Continue、Return
Break用来终止循环,Continue跳过当前,执行下一条,Return则直接返回。
// break
var sensitiveFeatures = Filter($layer, "class = 'sensitive'");
var largeAreasPresent;
for(var f in sensitiveFeatures){
if(!(AreaGeodetic(f) > 0)){
break;
}
largeAreasPresent = iif(f.ACRES > 5000, true, false);
}
// continue
var n = 0;
for(var i=1; i<100; i++) {
if (i % 2 == 1) {
continue;
}
n+=i;
}
return n;
6、While
while为true时就会一直循环下去。
Expects($feature, "*");
var prefix = "Year_";
var y = 1900;
var total = 0;
while(y <= 2020){
var fieldName = prefix + y;
if(HasKey($feature, fieldName)){
total += $feature[fieldName];
}
y+=10;
}
return total;