在js声明var和不声明var的区别,JS和java删除数组字符串重复数组
var 声明的变量,作用域是当前 function
没有声明的变量,直接赋值的话, 会自动创建变量
但作用域是全局的.
//-----------------
function doSth() {
a = "AAA";
}
doSth(); // 执行一次 doSth
alert(a); // 可以看到 "AAA"
//-----------------
如果用了 var
//-----------------
function doSth() {
var a = "AAA";
}
doSth(); // 执行一次 doSth
alert(a); // 出错!!! 变量未定义, 因为 doSth 中声明的变量作用域只是 doSth 函数.
js数组中去除重复值
详细出处参考:http://www.jb51.net/article/25939.htm
typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."
typeof 语法中的圆括号是可选项。
<script>
Array.prototype.del = function() {
var a = {}, c = [], l = this.length;
for (var i = 0; i < l; i++) {
var b = this[i];
var d = (typeof b) + b;
if (a[d] === undefined) {
c.push(b);
a[d] = 1;
}
}
return c;
}
alert([1, 1, 2, 3, 4, 5, 4, 3, 4, 4, 5, 5, 6, 7].del());
alert(["ad","bc","cd","ad"].del());
</script>
方法二:
js数组中去除重复值
//去重复数组
var arr = ["123","123","123","123","sfsdf","123","345","123","123","345","456","567","sdc"];
var str = [];
for(var i = 0,len = arr.length;i < len;i++){
! RegExp(arr[i],"g").test(str.join(",")) && (str.push(arr[i]));
}
alert(str);
详细出处参考:http://www.jb51.net/article/25939.htm
<script>
Array.prototype.distinct = function(){
var $ = this;
var o1 = {};
var o2 = {};
var o3 = [];
var o;
for(var i=0;o = $[i];i++){
if(o in o1){
if(!(o in o2)) o2[o] = o;
delete $[i];
}else{
o1[o] = o;
}
}
$.length = 0;
for(o in o1){
$.push(o);
}
for(o in o2){
o3.push(o);
}
return o3;
}
var a = [2,2,2,3,3,3,4,4,5,6,7,7];
alert("原数组:" + a);
alert("有重复的元素是:" + a.distinct());
alert("整理后的数组是:" + a);
alert("整理后的长度是:" + a.length)
</script>
详细出处参考:http://www.jb51.net/article/13727.htm
Javacode 删除重复数组的字符串
import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
public class Tests {
public static String[] array_unique(String[] a) {
// array_unique
List<String> list = new LinkedList<String>();
for(int i = 0; i < a.length; i++) {
if(!list.contains(a[i])) {
list.add(a[i]);
}
}
return (String[])list.toArray(new String[list.size()]);
}
public static void main(String[] args) {
String[] ar = {"dd","cc","ee","ff","gg","cc","ee"};
String[] s = array_unique(ar);
for(String aa : s) {
System.out.print(aa+" ");
}
}
}