typescript获取属性名_JavaScript如何获取一个对象的属性名

1. Object.getOwnPropertyNames()

返回一个对象本身所有属性名,不管是否可遍历。

Object.getOwnPropertyNames(Date)

// ["parse", "arguments", "UTC", "caller", "name", "prototype", "now", "length"]

2. Object.keys()

返回一个对象自身可比遍历属性名。

Object.keys(Date) // []

3. Object.prototype.hasOwnProperty()

返回一个布尔值,判断一个属性是否是对象自身属性,下面的例子中Date.length是Date自身的属性,Date.toString是继承的属性。

Date.hasOwnProperty('length') // true

Date.hasOwnProperty('toString') // false

4. in 运算符和 for…in 循环

in运算符返回一个布尔值,表示一个对象是否具有某个属性。它不区分该属性是对象自身的属性,还是继承的属性。

获得对象的所有可遍历属性(不管是自身的还是继承的),可以使用for...in循环。

var o1 = { p1: 123 };

var o2 = Object.create(o1, {

p2: { value: "abc", enumerable: true }

});

for (p in o2) {

console.info(p);

}

// p2

// p1

5. 获得对象的所有属性(不管是自身的还是继承的,也不管是否可枚举)

function inheritedPropertyNames(obj) {

var props = {};

while(obj) {

Object.getOwnPropertyNames(obj).forEach(function(p) {

props[p] = true;

});

obj = Object.getPrototypeOf(obj);

}

return Object.getOwnPropertyNames(props);

}

inheritedPropertyNames(Date)

// [

// "caller",

// "constructor",

// "toString",

// "UTC",

// ...

// ]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 HTML5 的 Canvas 元素来获取大幅图片的缩略图并显示。具体步骤如下: 1. 创建一个 HTML5 的 Canvas 元素。 2. 使用 JavaScript 的 Image 对象加载大幅图片。 3. 在 Image 对象的 onload 事件中,通过 Canvas 的 drawImage 方法将大幅图片绘制到 Canvas 上,并设置目标尺寸。 4. 使用 Canvas 的 toDataURL 方法将 Canvas 生成的缩略图转换为 Base64 编码的字符串。 5. 将 Base64 编码的字符串设置为 img 元素的 src 属性,即可显示缩略图。 下面是一个简单的实现示例: ```typescript import { ref } from 'vue'; export default { setup() { const thumbnail = ref(''); const createThumbnail = (file: File) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.src = URL.createObjectURL(file); img.onload = () => { const { width, height } = img; const targetWidth = 300; const targetHeight = (height * targetWidth) / width; canvas.width = targetWidth; canvas.height = targetHeight; ctx.drawImage(img, 0, 0, targetWidth, targetHeight); thumbnail.value = canvas.toDataURL(); }; }; const handleChange = (event: Event) => { const target = event.target as HTMLInputElement; const file = target.files && target.files[0]; if (file) { createThumbnail(file); } }; return { thumbnail, handleChange, }; }, }; ``` 在模板中,可以使用 v-if 或 v-show 根据 thumbnail 的值来显示或隐藏 img 元素。 ```html <template> <div> <input type="file" @change="handleChange" /> <img v-if="thumbnail" :src="thumbnail" /> </div> </template> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值